package com.wuwei.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.wuwei.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wuwei.entity.User;

/**
 * 用户控制器
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;


    @RequestMapping(value = "/login")
    public String login(User model, HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        //如果已经登录则直接返回到index方法中
        if (subject.isAuthenticated()) {
            /*return "redirect:/admin/index";*/
            subject.logout();
        }

        return "/login";
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User model, ModelMap modelMap) {
        //过滤是否存在
        User user = userService.findByUsername(model.getUsername());
        // 获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
        // 测试当前的用户是否已经被认证，即是否已经登陆
        // 调用Subject的isAuthenticated
        if (!currentUser.isAuthenticated()) {
            // 把用户名和密码封装为UsernamePasswordToken 对象
            UsernamePasswordToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
            token.setRememberMe(true);
            try {
                // 执行登陆,进入realm
                currentUser.login(token);
                modelMap.put("user", user);
                return "redirect:/admin/index";
            } catch (AuthenticationException ae) {
                System.out.println("登录失败--->" + ae.getMessage());
            }
        } else {
            return "redirect:/admin/index";
        }


        return "redirect:/login";
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }

        return "/login";
    }
}